package jprint.base.update;

import java.util.Objects;
import javax.annotation.Nonnull;

/**
 * <a href="https://semver.org/lang/zh-CN/">语义化版本 2.0.0</a>
 *
 * @author zw-zheng
 *
 * Created on 2021-02-04
 */
public final class Version {

    private static final Version sCurrent = new Version(Current.version);
    private final int major;
    private final int minor;
    private final int patch;

    private Version(String versionName) {
        String[] parts = versionName.split("[.]");
        major = Integer.parseInt(parts[0]);
        minor = Integer.parseInt(parts[1]);
        patch = Integer.parseInt(parts[2]);
    }

    Version(int major, int minor, int patch) {
        this.major = major;
        this.minor = minor;
        this.patch = patch;
    }

    public static Version of(@Nonnull String versionName) {
        return new Version(versionName);
    }

    public static Version current() {
        return sCurrent;
    }

    public int getCode() {
        // 1.2.3 => 10203
        return major * 1000 + minor * 100 + patch;
    }

    public String getName() {
        return String.format("%d.%d.%d", major, minor, patch);
    }

    public boolean isOlderThan(@Nonnull Version other) {
        return getCode() < other.getCode();
    }

    @Override public String toString() {
        return getName();
    }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Version version = (Version) o;
        return major == version.major &&
            minor == version.minor &&
            patch == version.patch;
    }

    @Override public int hashCode() {
        return Objects.hash(major, minor, patch);
    }
}
